package com.sanda.androidcourse.chapter07;


import static com.sanda.androidcourse.chapter07.MyServiceUseStart.ServiceTAG;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

import com.sanda.androidcourse.R;

public class MyServiceActivity extends AppCompatActivity {

    private boolean isBound = false;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            isBound = true;
            Toast.makeText(MyServiceActivity.this, "Service Bound", Toast.LENGTH_SHORT).show();
            Log.d(ServiceTAG, "Service Connected");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBound = false;
            Log.d(ServiceTAG, "Service Disconnected");
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_my_service);

        Button btnStartService = findViewById(R.id.btnStartService);
        Button btnStopService = findViewById(R.id.btnStopService);

        Button btnBindService = findViewById(R.id.btnBindService);
        Button btnUnbindService = findViewById(R.id.btnUnbindService);

        btnStartService.setOnClickListener(v -> {
            // 启动服务
            Intent serviceIntent = new Intent(MyServiceActivity.this, MyServiceUseStart.class);
            startService(serviceIntent);
        });

        btnStopService.setOnClickListener(v -> {
            // 停止服务
            Intent serviceIntent = new Intent(MyServiceActivity.this, MyServiceUseStart.class);
            stopService(serviceIntent);
        });

        btnBindService.setOnClickListener(v -> {
            // 绑定服务
            Intent serviceIntent = new Intent(MyServiceActivity.this, MyServiceUseBind.class);
            bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
        });

        btnUnbindService.setOnClickListener(v -> {
            // 解除绑定服务
            if (isBound) {
                unbindService(serviceConnection);
                isBound = false;
                Toast.makeText(MyServiceActivity.this, "Service Unbound", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isBound) {
            unbindService(serviceConnection);
        }
    }
}